<template>
  <div class="course-dashboard-container">
    <el-container>
      <el-header class="dashboard-header">
        <div class="header-left">
          <span class="welcome-text">您好，{{ teacherName }}！</span>
        </div>
        <div class="header-right">
          <el-button type="primary" icon="el-icon-plus" @click="addCourse()">创建新课程</el-button>
        </div>
      </el-header>

      <el-main class="dashboard-main">
        <h2>我的课程</h2>

        <el-form :inline="true" :model="formSearch" class="list-form-pv">
          <el-form-item>
            <el-input v-model="formSearch.title" placeholder="按课程名称搜索" @keydown.enter.native="getList(1)"
              clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList(1)">
              <i class="el-icon-search"></i> 查询
            </el-button>
          </el-form-item>
        </el-form>

        <div class="select2"
          :style='{ "width": "100%", "padding": "0 7%", "margin": "10px 0 0", "background": "#fff", "height": "auto", "order": "2" }'>
          <div
            :style='{ "padding": "0px", "margin": "4px 0", "borderColor": "#eee", "background": "none", "borderWidth": "0 0 1px", "width": "100%", "position": "relative", "borderStyle": "dashed", "height": "auto" }'
            class="list" v-for="(item, index) in selectOptionsList" :key="item.name">
            <div
              :style='{ "padding": "0 5px", "color": "#555", "textAlign": "right", "display": "inline-block", "width": "auto", "lineHeight": "32px", "fontSize": "14px" }'
              class="label">
              {{ item.name }}：
            </div>
            <div :style='{ "width": "auto", "display": "inline-block", "height": "auto" }' class="item-body">
              <div class="item" @click="selectClick2(item, -1)" :class="item.check == -1 ? 'active' : ''">全部</div>
              <div class="item" @click="selectClick2(item, index1)" :class="item.check == index1 ? 'active' : ''"
                v-for="(item1, index1) in item.list" :key="item1">{{ item1 }}</div>
            </div>
          </div>
        </div>

        <div class="list3 index-pv1" v-if="dataList.length > 0">
          <div v-for="(item, index) in dataList" :key="index" class="list-item animation-box">
            <div class="img-box">
              <img @click.stop="imgPreView(item.coverImageUrl)"
                :src="item.coverImageUrl && item.coverImageUrl.substr(0, 4) == 'http' ? item.coverImageUrl.split(',')[0] : (baseUrl + (item.coverImageUrl ? item.coverImageUrl.split(',')[0] : ''))"
                class="image" />
            </div>
            <div class="item-info">
              <div class="info-details">
                <div class="title">{{ item.title }}</div>
                <div class="course-type">{{ item.courseType }}</div>
                <div class="meta-item">
                  <span class="icon el-icon-thumb"></span>
                  <span class="text">{{ item.thumbsUpNum || 0 }}</span>
                </div>
                <div class="meta-item">
                  <span class="icon el-icon-star-off"></span>
                  <span class="text">{{ item.storeupnum || 0 }}</span>
                </div>
                <div class="meta-item">
                  <span class="icon el-icon-view"></span>
                  <span class="text">{{ item.clickNum || 0 }}</span>
                </div>
              </div>
              <div class="desc" v-html="item.description"></div>

              <div class="course-actions">
                <el-button type="primary" size="small" @click.stop="editCourse(item.id)">编辑</el-button>
                <el-button size="small" @click.stop="viewReviews(item.id)">查看评价</el-button>
                <el-button type="danger" size="small" @click.stop="deleteCourse(item.id)">删除</el-button>
              </div>
            </div>
          </div>
        </div>
        <el-empty v-else description="您还没有创建任何课程，快来创建第一个课程吧！"></el-empty>

        <el-pagination background id="pagination" class="pagination" :pager-count="7" :page-size="pageSize"
          :page-sizes="pageSizes" prev-text="<" next-text=">" :hide-on-single-page="false"
          :layout='["total", "prev", "pager", "next", "sizes", "jumper"].join()' :total="total"
          @current-change="curChange" @size-change="sizeChange" @prev-click="prevClick" @next-click="nextClick">
        </el-pagination>

      </el-main>
    </el-container>

    <CourseAddOrUpdate v-if="addFlag" ref="add" @refreshDataList="onRefreshDataList"  @dialogClosed="onDialogClosed"></CourseAddOrUpdate>

    <el-dialog title="预览图" :visible.sync="previewVisible" width="50%">
      <img :src="previewImg" alt="" style="width: 100%;">
    </el-dialog>
  </div>
</template>

<script>
import CourseAddOrUpdate from "./components/course-add-or-update.vue"; 
export default {
  name: 'CourseDashboard',
  data() {
    return {
      addFlag:false,
      baseUrl: '',
      teacherName: '未知教师',
      formSearch: {
        title: '',
        courseType: '',
      },
      courseTypeOptions: [],
      selectOptionsList: [],
      dataList: [],
      total: 0,
      pageSize: 8,
      pageSizes: [8, 16, 24, 32],
      currentPage: 1,
      previewImg: '',
      previewVisible: false,
    };
  },
  components: {
    CourseAddOrUpdate
  },
  created() {
    this.getTeacherInfo();

    // 初始化筛选项
    this.$http.get('common/option/course_type/course_type').then(res => {
      if (res.data.code === 0) {
        this.courseTypeOptions = res.data.data;
        this.selectOptionsList.push({
          name: '课程类型',
          list: this.courseTypeOptions,
          tableName: 'courseType',
          check: -1
        });
      }
    });
  },
  methods: {
    async getTeacherInfo() {
      const token = localStorage.getItem('frontToken');
      if (!token) {
        this.$router.push('/login');
        return;
      }

      let user = JSON.parse(localStorage.getItem('sessionForm'));
      if (user && user.username) {
        this.teacherName = user.username;
        this.getList(1);
        return;
      }

      try {
        const res = await this.$http.get(`teacher/session`, {
          headers: { 'Token': token }
        });

        if (res.data.code === 0 && res.data.data) {
          this.teacherName = res.data.data.username || res.data.data.name || '未知教师';
          localStorage.setItem('sessionForm', JSON.stringify(res.data.data));
          this.getList(1);
        } else {
          this.$message.error(res.data.msg || '获取教师信息失败！');
          if (res.data.code === 401) {
            this.$message.error('登录失效，请重新登录。');
            this.handleLogout();
          }
        }
      } catch (error) {
        this.$message.error('请求教师信息失败，请检查网络或稍后再试。');
        console.error('Fetch teacher info error:', error);
      }
    },

    async getList(page) {
      this.currentPage = page;
      const params = { page: this.currentPage, limit: this.pageSize };
      const searchWhere = {};

      if (this.formSearch.title?.trim()) {
        searchWhere.title = `%${this.formSearch.title}%`;
      }

      if (this.formSearch.courseType?.trim()) {
        searchWhere.courseType = this.formSearch.courseType;
      }

      const token = localStorage.getItem('frontToken');
      if (!token) {
        this.$message.warning('请先登录！');
        this.$router.push('/login');
        return;
      }

      const user = JSON.parse(localStorage.getItem('sessionForm'));
      if (user?.id) {
        searchWhere.teacherid = user.id;
      } else {
        this.$message.warning('无法获取教师ID，请确保登录信息完整！');
        return;
      }

      try {
        const res = await this.$http.get(`course/myCoursesAsTeacher`, {
          params: Object.assign(params, searchWhere),
          headers: { 'Token': token }
        });

        if (res.data.code === 0) {
          this.dataList = res.data.data.list;
          this.total = Number(res.data.data.total);
          this.pageSize = Number(res.data.data.pageSize);
        } else {
          this.$message.error(res.data.msg || '获取课程列表失败！');
          if (res.data.code === 401) {
            this.$message.error('登录失效，请重新登录。');
            this.handleLogout();
          }
        }
      } catch (error) {
        this.$message.error('请求课程列表失败，请检查网络或稍后再试。');
        console.error('Fetch courses error:', error);
      }
    },

    selectClick2(row, index) {
      row.check = index;
      this.formSearch[row.tableName] = index === -1 ? '' : row.list[index];
      this.getList(1);
    },

     onDialogClosed() {
    this.addOrUpdateFlag = false;
  },
  onRefreshDataList() {
    this.addOrUpdateFlag = false;

    this.getList(1);
  },
  
    async deleteCourse(courseId) {
      try {
        await this.$confirm('此操作将永久删除该课程, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });

        const token = localStorage.getItem('frontToken');
        if (!token) {
          this.$message.warning('请先登录！');
          this.$router.push('/login');
          return;
        }

        const res = await this.$http({
            url: `course/deleteMyCourse`,
            params: { id: courseId },
            method: "post"
        });

        if (res.data.code === 0) {
          this.$message.success('课程删除成功！');
          this.getList(this.currentPage);
        } else {
          this.$message.error(res.data.msg || '课程删除失败。');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除。');
        } else {
          this.$message.error('删除请求失败，请检查网络或稍后再试。');
          console.error('Delete course error:', error);
        }
      }
    },
    editCourse(courseId) {
      this.$router.push({ path: '/index/courseForm', query: { id: courseId } });
    },
    viewReviews(courseId) {
      this.$router.push({ path: '/index/courseReviews', query: { id: courseId } });
    },
    imgPreView(url) {
      this.previewImg = url;
      this.previewVisible = true;
    },
    handleLogout() {
      this.$confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        localStorage.removeItem('frontToken');
        localStorage.removeItem('sessionForm');
        this.$message.success('已退出登录。');
        this.$router.push('/login');
      }).catch(() => {
        this.$message.info('已取消退出。');
      });
    },

    addCourse(id) {
      this.addFlag = true;
      this.$nextTick(() => {
        this.$refs.add.init(id);
      });
    },
    curChange(page) {
      this.getList(page);
    },
    sizeChange(size) {
      this.pageSize = size;
      this.getList(1);
    },
    prevClick(page) {
      this.getList(page);
    },
    nextClick(page) {
      this.getList(page);
    },
  },
  beforeRouteUpdate(to, from, next) {
    if (to.query.page !== from.query.page || to.query.title !== from.query.title) {
      this.formSearch.title = to.query.title || '';
      this.getList(parseInt(to.query.page) || 1);
    }
    next();
  }
};
</script>


<style scoped>
/* 教师仪表盘容器 */
.course-dashboard-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 头部样式 */
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 0 20px;
  border-bottom: 1px solid #ebeef5;
}
.welcome-text {
  font-size: 18px;
  font-weight: bold;
}

/* 主内容区 */
.dashboard-main {
  padding: 20px;
}
h2 {
  margin-bottom: 20px;
  color: #333;
  text-align: center; /* 标题居中 */
}

/* 搜索表单 */
.list-form-pv {
  padding: 0px 0px 20px; /* 移除左右7%的padding，让其适应主要内容区 */
  margin: 20px 0 20px; /* 调整外边距 */
  display: flex;
  align-items: center;
  justify-content: center; /* 搜索框居中 */
  flex-wrap: wrap;
  background: #fff; /* 添加背景 */
  border-bottom: 1px solid #ddd;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05); /* 添加一点阴影 */
}
.list-form-pv .el-form-item {
  margin-bottom: 0px; /* 移除底部 margin，避免额外间距 */
}
.list-form-pv .el-input {
  width: 200px; /* 限制输入框宽度 */
}


/* 课程列表部分（仿照您的list3 index-pv1） */
.list3.index-pv1 {
  padding: 20px; /* 添加内边距 */
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;
  justify-content: center; /* 居中显示卡片 */
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05); /* 添加阴影 */
  margin-top: 20px;
}

.list-item {
  width: 320px; /* 固定卡片宽度，以便布局 */
  margin: 15px; /* 卡片之间的间距 */
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  display: flex; /* 让图片和信息并排 */
  flex-direction: column; /* 内容垂直排列 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05); /* 每个卡片独立阴影 */
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer; /* 鼠标悬停变手型 */
}

.list-item:hover {
  transform: translateY(-5px); /* 悬停上移 */
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1); /* 悬停阴影加深 */
}

.img-box {
  width: 100%; /* 图片宽度撑满卡片 */
  height: 180px; /* 图片固定高度 */
  overflow: hidden;
  border-bottom: 1px solid #f6f6f6;
}

.img-box .image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  transition: transform 0.3s ease;
}
.list-item:hover .img-box .image {
  transform: scale(1.05); /* 悬停图片放大 */
}


.item-info {
  padding: 15px;
  flex: 1; /* 占据剩余空间 */
  display: flex;
  flex-direction: column;
}

.info-details {
  display: flex;
  flex-wrap: wrap; /* 允许meta-item换行 */
  margin-bottom: 10px;
}

.info-details .title {
  width: 100%;
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.info-details .course-type {
  width: 100%;
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #606266;
  margin-right: 15px;
  margin-bottom: 5px; /* 适当间距 */
}
.meta-item .icon {
  margin-right: 5px;
  font-size: 14px;
}


.desc {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制显示三行描述 */
  -webkit-box-orient: vertical;
  margin-bottom: 15px;
}

.course-actions {
  display: flex;
  justify-content: flex-end; /* 按钮靠右对齐 */
  gap: 10px; /* 按钮间距 */
  margin-top: auto; /* 将按钮推到底部 */
}

/* 分页样式 */
.pagination {
  padding: 20px 0;
  margin: 20px auto;
  text-align: center;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}


.select2 .list .item-body .item {
	padding: 0 5px;
	color: #666;
	display: inline-block;
	font-size: 14px;
	line-height: 32px;
}

.select2 .list .item-body .item:hover {
	color: #F5BB00;
	background: none;
}

.select2 .list .item-body .item.active {
	color: #F5BB00;
	background: none;
}
</style>